<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="upload"
    >
      <img v-if="value" :src="value" class="avatar">
      <!-- <img v-if="true" src="http:feico-1308671654.cos.ap-shanghai.myqcloud.com/222.png" class="avatar"> -->
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>
<script>
// 下面是固定写法
const COS = require('cos-js-sdk-v5')
// 填写自己的腾讯云 cos 中的key和id(秘钥)
const cos = new COS({
  SecretId: 'AKID85mCLCm58cplQoulKcdNr4zd18yXruf9', // 身份识别ID
  SecretKey: 'EBrGOFp89vQebGfneDVWGjvqUrwlJHyO' // 身份秘钥
})
export default {
  name: 'UploadImg',
  props: {
    value: { type: String, default: '' }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  computed: {
  },
  created() {
  },
  methods: {
    upload(res) {
      // 选择了文件
      if (res.file) {
        //   执行上传操作
        cos.putObject({
          Bucket: 'feico-1308671654', // 存储桶名称
          Region: 'ap-shanghai', // 存储桶所在地域，必须字段
          Key: res.file.name, // 文件名
          StorageClass: 'STANDARD', // 标准上传模式
          Body: res.file // 上传对象
        }, (data) => {
          // 上传之后
          if (data.statusCode === 200) {
            const urlImg = `http://${data.Location}`
            this.$emit('input', urlImg)
          }
        }
        )
      }
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    }
  }
}
</script>
<style>
     .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
